package com.discuss.community.controller.interceptor;

import com.discuss.community.entity.LoginTicket;
import com.discuss.community.entity.User;
import com.discuss.community.service.UserService;
import com.discuss.community.util.CookieUtil;
import com.discuss.community.util.HostHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import springfox.documentation.spi.service.contexts.SecurityContext;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

@Component
@Slf4j
public class LoginTicketInterceptor implements HandlerInterceptor {
    
    /*@Autowired
    LoginTicketMapper loginTicketMapper;*/
    @Autowired
    UserService userService;
    @Autowired
    HostHolder hostHolder;
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String ticket = CookieUtil.getValue(request, "ticket");

        if(ticket != null) {
            LoginTicket loginTicket = userService.findLoginTicket(ticket);
            if(loginTicket != null && loginTicket.getStatus() == 0 && loginTicket.getExpired().after(new Date())) {
                User user = userService.getUserByUserId(loginTicket.getUserId());
                // 在本次请求持有用户
                hostHolder.setUser(user);
                // 构建用户认证结果，并存入 SecurityContext 中，以便 Security 进行授权
                Authentication authenticationToken = new UsernamePasswordAuthenticationToken(
                        user, user.getPassword(), userService.getAuthority(user.getId()));
                SecurityContextHolder.setContext(new SecurityContextImpl(authenticationToken));
            }
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        User user = hostHolder.getUser();
        if(user != null && modelAndView != null) {
            modelAndView.addObject("loginUser",user);
            log.info("登录信息 ===> {}", user);
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        hostHolder.clear();
        SecurityContextHolder.clearContext();
    }
}
